<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>基于DeepSeek的主动式智能导诊助手</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css">
    <style>
        :root {
            --primary-color: #3498db;
            --secondary-color: #2ecc71;
            --light-bg: #f8f9fa;
            --dark-text: #333;
            --light-text: #fff;
            --border-radius: 8px;
        }
        
        * {
            box-sizing: border-box;
            margin: 0;
            padding: 0;
        }
        
        body {
            font-family: 'Helvetica Neue', Arial, sans-serif;
            line-height: 1.6;
            color: var(--dark-text);
            background-color: #f0f2f5;
            max-width: 1200px;
            margin: 0 auto;
            padding: 20px;
        }
        
        header {
            display: flex;
            align-items: center;
            margin-bottom: 20px;
            padding-bottom: 15px;
            border-bottom: 1px solid #e0e0e0;
        }
        
        .logo {
            width: 50px;
            height: 50px;
            margin-right: 15px;
            background-color: var(--primary-color);
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            color: white;
            font-size: 24px;
        }
        
        h1 {
            color: var(--primary-color);
            margin: 0;
            font-size: 1.8rem;
        }
        
        .subtitle {
            font-size: 0.9rem;
            color: #777;
            margin-top: 5px;
        }
        
        .chat-container {
            border: 1px solid #ddd;
            border-radius: var(--border-radius);
            padding: 15px;
            height: 500px;
            overflow-y: auto;
            margin-bottom: 20px;
            background-color: white;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
        }
        
        .message {
            margin: 15px 0;
            padding: 12px 15px;
            border-radius: var(--border-radius);
            position: relative;
            max-width: 80%;
            animation: fadeIn 0.3s ease-in-out;
        }
        
        @keyframes fadeIn {
            from { opacity: 0; transform: translateY(10px); }
            to { opacity: 1; transform: translateY(0); }
        }
        
        .user-message {
            background-color: #e3f2fd;
            margin-left: auto;
            border-bottom-right-radius: 0;
            color: #0d47a1;
        }
        
        .bot-message {
            background-color: var(--light-bg);
            margin-right: auto;
            border-bottom-left-radius: 0;
            color: #37474f;
        }
        
        .bot-message::before {
            content: '';
            position: absolute;
            left: -10px;
            bottom: 0;
            border-right: 10px solid var(--light-bg);
            border-bottom: 10px solid transparent;
        }
        
        .user-message::after {
            content: '';
            position: absolute;
            right: -10px;
            bottom: 0;
            border-left: 10px solid #e3f2fd;
            border-bottom: 10px solid transparent;
        }
        
        .message-header {
            display: flex;
            align-items: center;
            margin-bottom: 8px;
        }
        
        .avatar {
            width: 30px;
            height: 30px;
            border-radius: 50%;
            margin-right: 10px;
            display: flex;
            align-items: center;
            justify-content: center;
            color: white;
            font-size: 14px;
        }
        
        .doctor-avatar {
            background-color: var(--primary-color);
        }
        
        .user-avatar {
            background-color: #ff7043;
        }
        
        .sender-name {
            font-weight: bold;
            font-size: 0.9rem;
        }
        
        .message-time {
            font-size: 0.7rem;
            color: #777;
            margin-left: 10px;
        }
        
        .input-container {
            display: flex;
            gap: 10px;
            position: relative;
        }
        
        textarea {
            flex-grow: 1;
            padding: 15px;
            border-radius: var(--border-radius);
            border: 1px solid #ddd;
            resize: none;
            font-family: inherit;
            font-size: 1rem;
            box-shadow: 0 2px 5px rgba(0, 0, 0, 0.05);
            transition: border-color 0.3s;
        }
        
        textarea:focus {
            outline: none;
            border-color: var(--primary-color);
        }
        
        button {
            padding: 0 20px;
            background-color: var(--primary-color);
            color: white;
            border: none;
            border-radius: var(--border-radius);
            cursor: pointer;
            font-weight: bold;
            transition: background-color 0.3s;
            display: flex;
            align-items: center;
            justify-content: center;
        }
        
        button:hover {
            background-color: #2980b9;
        }
        
        .quick-questions {
            display: flex;
            flex-wrap: wrap;
            gap: 10px;
            margin-top: 15px;
        }
        
        .quick-question {
            background-color: #f1f8fe;
            border: 1px solid #d1e6fa;
            border-radius: 20px;
            padding: 8px 15px;
            font-size: 0.9rem;
            cursor: pointer;
            transition: all 0.2s;
        }
        
        .quick-question:hover {
            background-color: #e3f2fd;
            transform: translateY(-2px);
        }
        
        .typing-indicator {
            display: flex;
            padding: 10px;
            margin-bottom: 10px;
        }
        
        .typing-dot {
            width: 8px;
            height: 8px;
            background-color: #aaa;
            border-radius: 50%;
            margin: 0 2px;
            animation: typingAnimation 1.5s infinite ease-in-out;
        }
        
        .typing-dot:nth-child(2) {
            animation-delay: 0.2s;
        }
        
        .typing-dot:nth-child(3) {
            animation-delay: 0.4s;
        }
        
        @keyframes typingAnimation {
            0% { transform: translateY(0); }
            50% { transform: translateY(-5px); }
            100% { transform: translateY(0); }
        }
        
        .disclaimer {
            font-size: 0.8rem;
            color: #777;
            text-align: center;
            margin-top: 20px;
            padding: 10px;
            border-top: 1px solid #eee;
        }
        
        /* 响应式设计 */
        @media (max-width: 768px) {
            body {
                padding: 10px;
            }
            
            .message {
                max-width: 90%;
            }
            
            h1 {
                font-size: 1.5rem;
            }
            
            .chat-container {
                height: 400px;
            }
        }
        
        @media (max-width: 480px) {
            .input-container {
                flex-direction: column;
            }
            
            button {
                height: 50px;
            }
            
            .message {
                max-width: 95%;
            }
            
            .quick-questions {
                flex-direction: column;
                gap: 5px;
            }
        }
    </style>
</head>
<body>
    <header>
        <div class="logo">
            <i class="fas fa-hospital"></i>
        </div>
        <div>
            <h1>院内智能导诊助手</h1>
            <p class="subtitle">基于DeepSeek，为您提供专业健康咨询</p>
        </div>
    </header>
    
    <div class="chat-container" id="chatContainer">
        <!-- 初始消息将在JS中添加 -->
    </div>
    
    <div class="input-container">
        <textarea id="userInput" rows="3" placeholder="请描述您的症状或健康问题..."></textarea>
        <button onclick="sendMessage()">
            <i class="fas fa-paper-plane"></i>
        </button>
    </div>
    
    <div class="quick-questions">
        <div class="quick-question" onclick="useQuickQuestion('我最近总是感到头痛，可能是什么原因？')">我最近总是感到头痛</div>
        <div class="quick-question" onclick="useQuickQuestion('高血压患者的日常饮食应该注意什么？')">高血压饮食建议</div>
        <div class="quick-question" onclick="useQuickQuestion('感冒发烧应该如何护理？')">感冒发烧护理</div>
        <div class="quick-question" onclick="useQuickQuestion('糖尿病患者应该如何控制血糖？')">糖尿病血糖控制</div>
    </div>
    
    <div class="disclaimer">
        <p>免责声明：本智能问诊助手提供的建议仅供参考，不能替代专业医生的诊断和治疗。如有紧急情况，请立即前往医院就诊。</p>
    </div>

    <script>
        const API_KEY = 'sk-vBvwY4XmFjV6HGzeFuJmWoMARPiNBL2M';
        const API_URL = 'https://api.sensenova.cn/compatible-mode/v1/chat/completions';
        let chatHistory = [];

        // 页面加载时显示欢迎消息
        window.onload = function() {
            const welcomeMessage = "您好！我是您的智能医疗助手。请描述您的症状或健康问题，我会尽力为您提供专业的建议。请注意，我提供的信息仅供参考，如有严重症状，请及时就医。";
            appendMessage('bot', welcomeMessage, '智能医疗助手', getCurrentTime());
            chatHistory.push({
                role: 'system',
                content: '你是一个专业的医疗助手，请根据用户描述的症状提供专业的健康建议，但要强调这只是初步建议，不能替代医生的诊断。'
            });
            chatHistory.push({
                role: 'assistant',
                content: welcomeMessage
            });
        }

        function useQuickQuestion(question) {
            document.getElementById('userInput').value = question;
            sendMessage();
        }

        function getCurrentTime() {
            const now = new Date();
            return `${now.getHours().toString().padStart(2, '0')}:${now.getMinutes().toString().padStart(2, '0')}`;
        }

        async function sendMessage() {
            const userInput = document.getElementById('userInput');
            const message = userInput.value.trim();
            if (!message) return;

            appendMessage('user', message, '我', getCurrentTime());
            userInput.value = '';
            
            // 添加用户消息到历史记录
            chatHistory.push({
                role: 'user',
                content: message
            });

            // 显示"正在输入"指示器
            const typingIndicator = document.createElement('div');
            typingIndicator.className = 'typing-indicator';
            typingIndicator.innerHTML = `
                <div class="avatar doctor-avatar"><i class="fas fa-user-md"></i></div>
                <div class="typing-dot"></div>
                <div class="typing-dot"></div>
                <div class="typing-dot"></div>
            `;
            document.getElementById('chatContainer').appendChild(typingIndicator);
            document.getElementById('chatContainer').scrollTop = document.getElementById('chatContainer').scrollHeight;

            try {
                const response = await fetch(API_URL, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'Authorization': `Bearer ${API_KEY}`,
                        'Accept': 'text/event-stream',
                        'Connection': 'keep-alive'
                    },
                    body: JSON.stringify({
                        model: 'DeepSeek-V3',
                        messages: chatHistory,
                        stream: true,
                        temperature: 0.7,
                        max_tokens: 2048
                    })
                });

                if (!response.ok) {
                    const errorData = await response.text();
                    throw new Error(`HTTP error! status: ${response.status}, message: ${errorData}`);
                }

                // 移除"正在输入"指示器
                typingIndicator.remove();
                
                // 创建新的消息元素
                const messageElement = appendMessage('bot', '', '智能医疗助手', getCurrentTime());
                const reader = response.body.getReader();
                let fullResponse = '';

                try {
                    while (true) {
                        const { done, value } = await reader.read();
                        if (done) break;

                        const text = new TextDecoder().decode(value);
                        const chunks = text.split('\n').filter(chunk => chunk.trim());

                        for (const chunk of chunks) {
                            if (!chunk.startsWith('data:')) continue;
                            if (chunk.includes('[DONE]')) continue;

                            try {
                                const json = JSON.parse(chunk.replace('data:', '').trim());
                                const content = json.choices[0]?.delta?.content;
                                if (content) {
                                    fullResponse += content;
                                    messageElement.querySelector('.message-content').innerHTML += formatMessage(content);
                                    chatContainer.scrollTop = chatContainer.scrollHeight;
                                }
                            } catch (e) {
                                console.error('JSON解析错误:', e);
                            }
                        }
                    }
                    
                    // 将完整的助手回复添加到历史记录
                    chatHistory.push({
                        role: 'assistant',
                        content: fullResponse
                    });
                    
                    // 分析回复内容，推荐相关科室
                    recommendDepartment(message, fullResponse);
                    
                } catch (e) {
                    console.error('流读取错误:', e);
                } finally {
                    reader.releaseLock();
                }
            } catch (error) {
                // 移除"正在输入"指示器
                if (typingIndicator) typingIndicator.remove();
                appendMessage('bot', `抱歉，出现了错误：${error.message}`, '智能医疗助手', getCurrentTime());
            }
        }

        // 科室数据库
        const departments = [
            { name: '内科', keywords: ['发热', '头痛', '咳嗽', '胸痛', '心悸', '呼吸困难', '腹痛', '腹泻', '便秘', '恶心', '呕吐', '乏力', '疲劳', '高血压', '糖尿病', '心脏病'] },
            { name: '外科', keywords: ['外伤', '骨折', '脱位', '扭伤', '烧伤', '烫伤', '切割伤', '肿块', '肿瘤', '疼痛', '手术'] },
            { name: '妇产科', keywords: ['月经', '痛经', '闭经', '不孕', '怀孕', '孕吐', '产前', '产后', '乳房', '宫颈', '子宫', '卵巢'] },
            { name: '儿科', keywords: ['婴儿', '幼儿', '儿童', '发育', '生长', '疫苗', '免疫', '小儿'] },
            { name: '眼科', keywords: ['视力', '眼睛', '眼痛', '眼红', '眼干', '眼花', '近视', '远视', '散光', '白内障', '青光眼'] },
            { name: '耳鼻喉科', keywords: ['耳朵', '耳痛', '耳鸣', '听力', '鼻子', '鼻塞', '流鼻血', '打喷嚏', '咽喉', '扁桃体', '嗓子'] },
            { name: '口腔科', keywords: ['牙痛', '蛀牙', '牙龈', '口腔', '口臭', '舌头', '牙齿', '牙龈炎', '牙周炎'] },
            { name: '皮肤科', keywords: ['皮疹', '瘙痒', '湿疹', '痤疮', '皮肤', '脱发', '斑点', '红斑', '过敏', '荨麻疹'] },
            { name: '神经内科', keywords: ['头晕', '头痛', '失眠', '抑郁', '焦虑', '记忆力', '晕厥', '癫痫', '中风', '脑卒中', '帕金森'] },
            { name: '精神科', keywords: ['抑郁症', '焦虑症', '强迫症', '精神分裂', '躁狂', '失眠', '心理', '精神', '情绪'] },
            { name: '骨科', keywords: ['骨折', '关节痛', '腰痛', '颈椎', '腰椎', '膝盖', '肩膀', '骨质疏松', '关节炎', '风湿'] },
            { name: '泌尿外科', keywords: ['尿频', '尿急', '尿痛', '尿血', '尿路', '肾脏', '膀胱', '前列腺', '结石'] },
            { name: '心胸外科', keywords: ['心脏', '胸痛', '心绞痛', '心肌梗塞', '冠心病', '心律不齐', '心脏瓣膜', '主动脉'] },
            { name: '肿瘤科', keywords: ['肿瘤', '癌症', '恶性', '良性', '化疗', '放疗', '肿块'] },
            { name: '内分泌科', keywords: ['甲状腺', '糖尿病', '肥胖', '代谢', '内分泌', '激素', '肾上腺'] },
            { name: '感染科', keywords: ['发热', '感染', '病毒', '细菌', '真菌', '寄生虫', '传染病', '艾滋病', '肝炎'] },
            { name: '急诊科', keywords: ['急性', '突发', '剧痛', '昏迷', '休克', '抢救', '意外', '事故'] }
        ];

        // 根据用户症状和AI回复推荐科室
        function recommendDepartment(userMessage, aiResponse) {
            const combinedText = userMessage + ' ' + aiResponse;
            let matchedDepartments = [];
            
            // 遍历科室数据库，查找匹配的关键词
            departments.forEach(dept => {
                let matchCount = 0;
                dept.keywords.forEach(keyword => {
                    if (combinedText.includes(keyword)) {
                        matchCount++;
                    }
                });
                
                if (matchCount > 0) {
                    matchedDepartments.push({
                        name: dept.name,
                        score: matchCount,
                        matchedKeywords: dept.keywords.filter(keyword => combinedText.includes(keyword))
                    });
                }
            });
            
            // 按匹配分数排序
            matchedDepartments.sort((a, b) => b.score - a.score);
            
            // 取前三个最匹配的科室
            const topDepartments = matchedDepartments.slice(0, 3);
            
            if (topDepartments.length > 0) {
                displayDepartmentRecommendation(topDepartments);
            }
        }
        
        // 显示科室推荐
        function displayDepartmentRecommendation(departments) {
            const chatContainer = document.getElementById('chatContainer');
            const recommendDiv = document.createElement('div');
            recommendDiv.className = 'department-recommendation';
            recommendDiv.style.margin = '15px 0';
            recommendDiv.style.padding = '15px';
            recommendDiv.style.backgroundColor = '#f0f7ff';
            recommendDiv.style.borderRadius = 'var(--border-radius)';
            recommendDiv.style.borderLeft = '4px solid var(--primary-color)';
            
            let html = `
                <div style="font-weight: bold; margin-bottom: 10px; color: var(--primary-color);">
                    <i class="fas fa-hospital-user"></i> 科室推荐
                </div>
                <div style="font-size: 0.9rem; margin-bottom: 10px;">
                    根据您的描述，建议您可以考虑以下科室就诊：
                </div>
                <div style="display: flex; flex-wrap: wrap; gap: 10px;">
            `;
            
            departments.forEach((dept, index) => {
                html += `
                    <div style="background-color: ${index === 0 ? 'var(--primary-color)' : '#e3f2fd'}; 
                                color: ${index === 0 ? 'white' : 'var(--primary-color)'};
                                padding: 8px 15px; 
                                border-radius: 20px; 
                                font-weight: ${index === 0 ? 'bold' : 'normal'};
                                display: flex;
                                align-items: center;">
                        <i class="fas fa-stethoscope" style="margin-right: 5px;"></i>
                        ${dept.name}
                        ${index === 0 ? ' <span style="font-size: 0.8rem; margin-left: 5px;">(最佳匹配)</span>' : ''}
                    </div>
                `;
            });
            
            html += `
                </div>
                <div style="font-size: 0.8rem; margin-top: 10px; color: #777;">
                    <i class="fas fa-info-circle"></i> 请注意：此推荐仅供参考，具体就诊科室请以医院分诊为准。
                </div>
            `;
            
            recommendDiv.innerHTML = html;
            chatContainer.appendChild(recommendDiv);
            chatContainer.scrollTop = chatContainer.scrollHeight;
        }

        function appendMessage(role, content, sender, time) {
            const chatContainer = document.getElementById('chatContainer');
            const messageDiv = document.createElement('div');
            messageDiv.className = `message ${role}-message`;
            
            // 创建消息头部（头像、名称、时间）
            const messageHeader = document.createElement('div');
            messageHeader.className = 'message-header';
            
            // 创建头像
            const avatar = document.createElement('div');
            avatar.className = `avatar ${role === 'bot' ? 'doctor-avatar' : 'user-avatar'}`;
            avatar.innerHTML = role === 'bot' ? '<i class="fas fa-user-md"></i>' : '<i class="fas fa-user"></i>';
            
            // 创建发送者名称
            const senderName = document.createElement('div');
            senderName.className = 'sender-name';
            senderName.textContent = sender;
            
            // 创建时间
            const messageTime = document.createElement('div');
            messageTime.className = 'message-time';
            messageTime.textContent = time;
            
            // 组装消息头部
            messageHeader.appendChild(avatar);
            messageHeader.appendChild(senderName);
            messageHeader.appendChild(messageTime);
            
            // 创建消息内容
            const messageContent = document.createElement('div');
            messageContent.className = 'message-content';
            messageContent.innerHTML = formatMessage(content);
            
            // 组装完整消息
            messageDiv.appendChild(messageHeader);
            messageDiv.appendChild(messageContent);
            
            chatContainer.appendChild(messageDiv);
            chatContainer.scrollTop = chatContainer.scrollHeight;
            return messageDiv;
        }
        
        // 格式化消息内容，处理换行和链接
        function formatMessage(content) {
            if (!content) return '';
            
            // 将内容先进行Markdown解析
            let formatted = content;
            
            // 处理标题 (h1-h6)
            formatted = formatted.replace(/^(#{1,6})\s+(.+)$/gm, function(match, hashes, text) {
                const level = hashes.length;
                return `<h${level} style="margin: 10px 0; color: var(--primary-color);">${text}</h${level}>`;
            });
            
            // 处理粗体
            formatted = formatted.replace(/\*\*(.*?)\*\*/g, '<strong>$1</strong>');
            
            // 处理斜体
            formatted = formatted.replace(/\*(.*?)\*/g, '<em>$1</em>');
            
            // 处理有序列表
            formatted = formatted.replace(/^\d+\.\s+(.+)$/gm, '<li>$1</li>');
            formatted = formatted.replace(/(<li>.*<\/li>(\n|$))+/g, '<ol style="margin-left: 20px;">$&</ol>');
            
            // 处理无序列表
            formatted = formatted.replace(/^[\*\-]\s+(.+)$/gm, '<li>$1</li>');
            formatted = formatted.replace(/(<li>.*<\/li>(\n|$))+/g, '<ul style="margin-left: 20px;">$&</ul>');
            
            // 处理引用
            formatted = formatted.replace(/^>\s+(.+)$/gm, '<blockquote style="border-left: 3px solid var(--primary-color); padding-left: 10px; color: #666;">$1</blockquote>');
            
            // 处理代码块
            formatted = formatted.replace(/```([\s\S]*?)```/g, '<pre style="background-color: #f5f5f5; padding: 10px; border-radius: 5px; overflow-x: auto;"><code>$1</code></pre>');
            
            // 处理行内代码
            formatted = formatted.replace(/`([^`]+)`/g, '<code style="background-color: #f5f5f5; padding: 2px 4px; border-radius: 3px;">$1</code>');
            
            // 处理分隔线
            formatted = formatted.replace(/^---+$/gm, '<hr style="border: 0; border-top: 1px solid #eee; margin: 10px 0;">');
            
            // 将换行符转换为<br>（在处理完Markdown后）
            formatted = formatted.replace(/\n/g, '<br>');
            
            // 将URL转换为可点击的链接
            formatted = formatted.replace(
                /(https?:\/\/[^\s]+)/g, 
                '<a href="$1" target="_blank" style="color:var(--primary-color);text-decoration:underline;">$1</a>'
            );
            
            // 突出显示医学术语
            const medicalTerms = [
                '高血压', '糖尿病', '心脏病', '冠心病', '脑卒中', '肺炎', 
                '哮喘', '慢性阻塞性肺疾病', '肝炎', '肾炎', '胃炎', '溃疡', 
                '贫血', '白血病', '甲状腺', 'ndepht', '焦虑症'
            ];
            
            medicalTerms.forEach(term => {
                const regex = new RegExp(`(${term})`, 'g');
                formatted = formatted.replace(regex, '<span style="color:var(--secondary-color);font-weight:bold;">$1</span>');
            });
            
            return formatted;
        }
    </script>
</body>
</html>